package com.yx.interceptor;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.yx.constatns.AuthConstatns;
import com.yx.constatns.OrderConstants;
import com.yx.utils.OrderUtils;
import com.yx.vo.Customer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Classname DynamicDataSourceAnnotationInterceptor
 * @Date 2021/07/21 15:35
 * @Author by yx
 * @Description TODO:
 */
@Component
@Slf4j
public class DynamicDataSourceAnnotationInterceptor implements HandlerInterceptor {

    // 调用方法获取
    public Integer getTableIndex() {
        return tableIndexTheLocal.get();
    }

    // 建立一个threadLocal 在同一个线程中可以安全的获取本线程中的数据--->用于获取表名
    private ThreadLocal<Integer> tableIndexTheLocal = new ThreadLocal<>();

    @Autowired
    private OrderUtils orderUtils;

    /**
     * 1.计算出数据库编号
     * 2、计算出表的编号
     * 3、设置数据源
     *
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String requestUri = request.getRequestURI();
        log.debug("请求路径: {}", requestUri);

        if (requestUri.indexOf("/orderController/updateOrderStatus") >= 0 || requestUri.indexOf("/orderController/wxgetOrderByOid") >= 0 ||
                requestUri.indexOf("/orderController/getOrderByOid") >= 0) {
            log.debug("进入了放行的路径");
            return true;
        }
        //1.获取当前登录的用户
        Customer customer = (Customer) request.getSession().getAttribute(AuthConstatns.AUTH_SESSION);

        // 判断用户是否登录
        if (customer == null) {
            // 未登录,重定向至用户登录页面
            response.sendRedirect("http://localhost/auth/login.html");
        }

        Integer uid = customer.getId();
        //获取用户id后四位
        Integer lastUserId = Integer.valueOf(orderUtils.lastUserId(uid));

        // 计算数据库编号(用户id后四位%数据库的数量)
        Integer dbIndex = (lastUserId % OrderConstants.ORDER_DB_SIZE) + 1;

        // 创建数据源key
        String dataSourceKey = OrderConstants.ORDER_DB_PRE + dbIndex;

        // 设置数据源
        DynamicDataSourceContextHolder.push(dataSourceKey);

        // 计算订单的表的编号(在插入的时候才会使用这个值，我在这个地方一起计算出来)
        Integer tableIndex = (lastUserId / OrderConstants.ORDER_DB_SIZE % OrderConstants.ORDER_TABLE_SIZE) + 1;

        // 放入threadLocal中,方便mapper取
        tableIndexTheLocal.set(tableIndex);

        log.debug("【DynamicDataSourceInterceptor】当前线程id:{}", Thread.currentThread().getId());
        log.debug("用户Id后四位:{}", lastUserId);
        log.debug("数据库的编号是:{}", dbIndex);
        log.debug("数据表的编号是:{}", tableIndex);

        // 放行
        return true;

    }
}
